/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;
import db.H2Adapter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.xml.sax.SAXException;
import xml.jxb.Description;
import xml.jxb.ObjectFactory;
import xml.jxb.Project;

/**
 *
 * @author abnormal
 */
@WebServlet(name = "H2Servlet", urlPatterns = {"/H2Servlet"})
public class H2Servlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        H2Adapter h2 = null;
        String _do = "";
        try {
            h2 = new H2Adapter();
            _do = request.getParameter("do");
            if (_do == null) {
                try {
                    response.sendError(501, "NOP");
                    return;
                } catch (IOException ex) {
                    Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
            try {
                response.sendError(500);
            } catch (IOException ex1) {
                Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex1);
            }
        } catch (SQLException ex) {
            Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
            try {
                response.sendError(500);
            } catch (IOException ex1) {
                Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
        //*metoder*************************************************************//
        if (_do.equals("getlist")) {
            try {
                ArrayList<Project> projects = h2.getProjectList((Integer) request.getSession().getAttribute("id"));
                JsonObject json = new JsonObject();
                Gson gson = new Gson();
                int i = 1;
                for (Project p : projects) {
                    Description des = p.getDescription();
                    JsonObject proj = new JsonObject();
                    proj.addProperty("name", des.getProjectName());
                    proj.addProperty("author", des.getProjectAuthor());
                    proj.addProperty("revision", des.getProjectRevision());
                    proj.addProperty("units", p.getUnits().getUnit().size());
                    proj.addProperty("profiles", 5);
                    json.add((i++ + ":" + des.getProjectName()), proj);
                }
                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.write(gson.toJson(json));

            } catch (SQLException ex) {
                Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
                h2.getCon().close();
            } catch (JAXBException ex) {
                Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
                h2.getCon().close();
            } catch (SAXException ex) {
                Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
                h2.getCon().close();
            } catch (Exception ex) {
                Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
                h2.getCon().close();
            }
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(H2Servlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void SaveNewProject(HttpServletRequest request, HttpServletResponse response) throws DatatypeConfigurationException {
        ObjectFactory of = new ObjectFactory();
        Project proj = of.createProject();
        proj.setDescription(of.createDescription());
        proj.setUnits(of.createUnits());
        proj.setProfiles(of.createProfiles());
        proj.getDescription().setProjectAuthor(request.getParameter("name"));
        proj.getDescription().setProjectName(request.getParameter("project_name"));
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(new java.util.Date(System.currentTimeMillis()));
        XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
        proj.getDescription().setProjectCreationDate(date2);
        proj.getDescription().setProjectRevision(1);





    }

    public void SaveNewProjectValidateAllFields(HttpServletRequest request, HttpServletResponse response) {
    }
}
